package microcredit.gui.handler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import microcredit.gui.selector.IFilter;
import microcredit.model.Member;
import microcredit.model.MemberToTrainingType;

abstract class FilterWrapper<S, T> implements IFilter<T> {

	private final IFilter<S> delegate;
	
	public FilterWrapper(IFilter<S> delegate) {
		this.delegate = delegate;
	}
	
	@Override
	public String getLabel() {
		return delegate.getLabel();
	}

	@Override
	public List<? extends Object> getValues() {
		return delegate.getValues();
	}

	@Override
	public Object getSelectedValue() {
		return delegate.getSelectedValue();
	}

	@Override
	public void filter(Object exp, List<T> entities) {
		Map<S, T> converterMapping = new HashMap<S, T>();
		List<S> toFilter = new ArrayList<S>();
		for (T t : entities) {
			S s = convertForm(t);
			toFilter.add(s);
			converterMapping.put(s, t);
		}
		delegate.filter(exp, toFilter);
		entities.clear();
		for (S s : toFilter) {
			T t = converterMapping.get(s);
			entities.add(t);
		}
	}
	
	protected abstract S convertForm( T source);
	
	
	public static IFilter<MemberToTrainingType> wrapMemberAsMemberToTrainingType(IFilter<Member> source) {
		return new FilterWrapper<Member, MemberToTrainingType>(source) {
			@Override
			protected Member convertForm(MemberToTrainingType source) {
				return source.getMember();
			}
		};
	}
	
}